/**
 *  This software is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Use this application at your own risk.
 *
 *  Copyright (c) 2011 by Orfeo Morello.
 */
package com.localstreamer.mobile;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

import com.markupartist.sthlmtraveling.MyLocationManager;
import com.markupartist.sthlmtraveling.MyLocationManager.MyLocationFoundListener;

public class SplashScreen extends Activity  implements LocationListener{
	    
	   private static final int STOPSPLASH = 0;
	   //time in milliseconds
	   private static final long SPLASHTIME = 5000;
	   
		protected Context applicationContext;
		protected Address address;
		private LocationManager locationManager;
		private MyLocationManager mMyLocationManager;
	    private Location currentLocation;
	    private Geocoder geocoder; 
	  
	    private ImageView splash;

	    //handler for splash screen
	    private Handler splashHandler = new Handler() {
	       /* (non-Javadoc)
	        * @see android.os.Handler#handleMessage(android.os.Message)
	        */
	       @Override
	       public void handleMessage(Message msg) {
	          switch (msg.what) {
	          case STOPSPLASH:
	             //remove SplashScreen from view
	             splash.setVisibility(View.GONE);
	             break;
	          }
	          super.handleMessage(msg);
	       }
	    };
	    
	    
	   /** Called when the activity is first created. */
	   @Override
	   public void onCreate(Bundle icicle) {
		       try {
				this.setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
				   super.onCreate(icicle);
				   setContentView(R.layout.main);
				   
    			   boolean isOnline=Utilities.isNetworkAvailable(this);
					
				   if(isOnline)
				   {
				   
				        splash = (ImageView) findViewById(R.id.splashscreen);
				        //splash.setVisibility(View.VISIBLE);
				        
				        Message msg = new Message();
				        msg.what = STOPSPLASH;
				        splashHandler.sendMessageDelayed(msg, SPLASHTIME);
				        
						// Get the location manager
						locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
						geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
						/*
						 List<String> providers = locationManager.getProviders(true);
                         
						 String lastProvider="";
						 
					     for (int i=providers.size()-1; i>=0; i--) {
					    	       lastProvider = providers.get(i);
					        	   currentLocation = locationManager.getLastKnownLocation(lastProvider);
					               if (currentLocation != null) break;
					     }
						
						if (currentLocation != null)
				    	{
							reverseGeocodeLookup(currentLocation);
				    	}
				    	else
				    	{
				    	*/
				    		boolean isGpsNotEnabled =!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)||!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
				    		 if (isGpsNotEnabled){
				    	          createGpsDisabledAlert();
				    	     }
				    		 else
				    		 {
				    			    mMyLocationManager = new MyLocationManager(locationManager);
				    		        mMyLocationManager.requestLocationUpdates(new MyLocationFoundListener() {
				    		            
				    		            @Override
				    		            public void onMyLocationFound(Location location) 
				    		            {
				    		            	if(location!=null)
				    						{
				    							reverseGeocodeLookup(location);
				    						}
				    						else
				    						{
				    				    		 new AlertDialog.Builder(SplashScreen.this).setTitle("Local streamer").setMessage("Unable to detect your location using "+location.getProvider()).setNegativeButton("OK", new DialogInterface.OnClickListener() {
				    						          public void onClick(DialogInterface dialog, int whichButton) {
				    						        	  android.os.Process.killProcess(android.os.Process.myPid());		    	          }
				    						     }).show();
				    						}
				    		            }
				    		        });
				    		        mMyLocationManager.setLocationListener(this);
				    		 }
				    	//}
				   }
				   else
				   {
					    new AlertDialog.Builder(SplashScreen.this).setTitle("Local streamer").setMessage("No internet connection available!").setNegativeButton("OK", new DialogInterface.OnClickListener() {
					          public void onClick(DialogInterface dialog, int whichButton) {
					        	  android.os.Process.killProcess(android.os.Process.myPid());		    	          }
					     }).show();
				   }
			} catch (Exception e) {
				Log.d("SplashScreen.onCreate:",e.getMessage());
			    new AlertDialog.Builder(SplashScreen.this).setTitle("Local streamer").setMessage("Can't detect internet connection").setNegativeButton("OK", new DialogInterface.OnClickListener() {
			          public void onClick(DialogInterface dialog, int whichButton) {
			        	  android.os.Process.killProcess(android.os.Process.myPid());		    	          }
			     }).show();
			}
	   } 
	   

	   private void createGpsDisabledAlert()
	   {
		   AlertDialog.Builder builder = new AlertDialog.Builder(this);
		   builder.setMessage("Your GPS and Location by Wireless Network are disabled! Would you like to enable?")
		        .setCancelable(false)
		        .setPositiveButton("Enable",
		             new DialogInterface.OnClickListener(){
		             public void onClick(DialogInterface dialog, int id){
		                  showGpsOptions();
		             }
		        });
		        builder.setNegativeButton("No thanks",
		             new DialogInterface.OnClickListener(){
		             public void onClick(DialogInterface dialog, int id){
		                  dialog.cancel();
		             }
		        });
		   AlertDialog alert = builder.create();
		   alert.show();
	   }

	   private void showGpsOptions(){
	   		Intent gpsOptionsIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
	   		startActivity(gpsOptionsIntent);
	   }
	   
	   public void reverseGeocodeLookup(Location location)
	   {
			// Kickoff an asynchronous task to fire the reverse geocoding
	   		// request off to google
		   	this.currentLocation = location;
	   		ReverseGeocodeLookupTask task = new ReverseGeocodeLookupTask();
	   		task.applicationContext = this;
	   		task.execute();
	   }
		
		public class ReverseGeocodeLookupTask extends AsyncTask <Void, Void, String>
	    {
	    	private ProgressDialog dialog;
	    	protected Context applicationContext;
	    	
	    	@Override
	    	protected void onPreExecute()
	    	{
	    		//this.dialog = ProgressDialog.show(applicationContext, "Please wait....",  "Requesting reverse geocode lookup", true);
	    	}
	    	
			@Override
			protected String doInBackground(Void... params) 
			{
				String localityName = "";
				
				if (currentLocation != null)
				{
					try {
						List<Address> addresses=null;
						try {
							 addresses = geocoder.getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(), 1);
						} catch (Exception e) {
							addresses = ReverseGeocode.getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(), 1);
						}
						if(addresses!=null&&addresses.size()>0)
						{
							address = addresses.get(0);
							localityName = address.getAddressLine(0);	
						}
					} catch (Exception e) {
						
					}
				}
				
				return localityName;
			}
			
			@Override
			protected void onPostExecute(String result)
			{
				if(result.trim().equals(""))
				{
		    	    Builder builder = new AlertDialog.Builder(SplashScreen.this).setTitle("Local streamer").setMessage("Slow internet connection, restart.");
		    	    builder.setNegativeButton("Quit", new DialogInterface.OnClickListener() {
		    	          public void onClick(DialogInterface dialog, int whichButton) {
		    	        	  android.os.Process.killProcess(android.os.Process.myPid());		    	          }
		    	     }).show();
				}
				else
				{
					String lat = String.valueOf(address.getLatitude());
					String lng = String.valueOf(address.getLongitude());
					String c = address.getLocality();
					String l = address.getLocale().getCountry().toLowerCase();

					String uri="";
					try {
						uri="http://www.localstreamer.com/mobile/realtime/c/"+URLEncoder.encode(c, "utf-8")+"/l/"+l+"/lat/"+lat+"/lng/"+lng+"/key/"+new Date().getTime();
					} catch (UnsupportedEncodingException e) {
						
					}
					Utilities.showToast("Please wait ... loading informations ",applicationContext);
					Intent intent = new Intent(SplashScreen.this, RemoteBrowser.class);
					Bundle b = new Bundle();
					b.putString("customUrl", uri);
					intent.putExtras(b);
					startActivity(intent);
				}
			}
	    }
	   
		@Override
		public boolean onCreateOptionsMenu(Menu menu) {
			menu.add(0, 1001, 0, "Quit");
			return super.onCreateOptionsMenu(menu); 
		}
 
		@Override
		public boolean onOptionsItemSelected(MenuItem item) 
		{
			switch (item.getItemId()) 
			{
				case 1001:
				this.finish();
				break;
			}
			return super.onOptionsItemSelected(item);
		}
		
	   /** Register for the updates when Activity is in foreground */
		@Override
		protected void onResume() {
			super.onResume();
			//locationManager.removeUpdates(this);
		}

		/** Stop the updates when Activity is paused */
		@Override
		protected void onPause() {
			super.onPause();
			//locationManager.removeUpdates(this);
		}

		@Override
		protected void onDestroy() {
			//locationManager.removeUpdates(this);
			super.onDestroy();
		}
		
		@Override
		protected void onStop() {
			/* may as well just finish since saving the state is not important for this toy app */
			finish();
			super.onStop();
		}
	
		    @Override
		    public void onLocationChanged(Location location) {
		       
		    }

		    @Override
		    public void onProviderDisabled(String provider) {

		        
		    }

		    @Override
			public void onProviderEnabled(String provider) {

		        
		    }

		    @Override
		    public void onStatusChanged(String provider, int status, Bundle extras) {

		        
		    }
}